"use strict";

const Controller = require("egg").Controller;

class UserController extends Controller {
    async zhuce() {
        //解析请求体参数
        const { username, password, nickname } = this.ctx.request.body;
        //查询此用户是否存在
        let user = await this.service.user.cha(
            username,
            this.ctx.helper.enCrypto(password) //验证密码加密
        );
        //判断用户是否存在
        if (user) {
            this.ctx.body = {
                code: 403,
                msg: "此用户存在",
            };
            return;
        }
        //判断参数是否为空
        if (!username || !password || !nickname) {
            this.ctx.body = {
                code: 401,
                msg: "参数为空",
            };
            return;
        }
        //注册 要用户名 密码
        let res = await this.service.user.zhuce(username, password, nickname);
        if (res.affectedRows === 1) {
            this.ctx.body = {
                code: 201,
                msg: "注册成功",
            };
        }
    }
    //查询数据
    async chaxun() {
        const res = await this.service.user.chaxun(); //定义查询
        this.ctx.body = {
            code: 200,
            data: res,
            msg: "查询成功",
        };
        return; //返回数据
    }
    //登录
    async denglu() {
        const { username, password } = this.ctx.request.body;
        //登录的时候需要查询数据库的名字
        let user = await this.service.user.cha(
            username,
            //password  //不需要加密验证的
            this.ctx.helper.enCrypto(password) //密码加密
        );
        //判断该名字是否存在
        if (!user) {
            this.ctx.body = {
                code: 401,
                msg: "输入正确的用户名密码",
            };
            return;
        }
        //验证密码是否正确
        if (user.password !== this.ctx.helper.enCrypto(password)) {
            this.ctx.body = {
                code: 200,
                msg: "密码错误",
            };
            return;
        }
        //过滤敏感字段
        delete user.password;
        //获取token
        const token = this.ctx.helper.getToken({ ...user });
        //用户存在登录成功
        this.ctx.body = {
            code: 202,
            data: user,
            msg: "登录成功",
        };
        return;
    }
}

module.exports = UserController;
